package com.putao.album.util;

import android.content.Context;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.putao.album.R;
import com.putao.album.application.GlobalApplication;
import com.putao.album.dialog.DialogBuilderFactory;
import com.putao.album.dialog.LoadingDialogBuilder;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;

/**
 * Created by jidongdong on 15/4/21.
 */
public class HttpRequestUtil {

    private static Context context;

    static {
        context = GlobalApplication.getInstance();
    }

    private static LoadingDialogBuilder mLoadingDialogBuilder;
    private static boolean mFlagShowLoading = false;

    public static HashMap buildHttpRequestParams(HashMap map) {
        if (map != null) {
            map.put("version", AppHelper.getVersionCode() + "");
            map.put("platform_id", PuTaoConstants.PLATFORM_ID);
            map.put("appid", PuTaoConstants.APP_ID);
            map.put("client_type", PuTaoConstants.CLIENT_TYPE);

            //以下参数每次请求用于用户验证
            map.put("token", CommonUtils.getTokenId());
            map.put("device_id", AppHelper.getDeviceId());

            String uid = CommonUtils.getUsrId();
            map.put("uid", uid);

        }
        return map;
    }

    /**
     * Get请求带参数是否显示加载状态
     *
     * @param context
     * @param url
     * @param params
     * @param showLoading
     * @param listener
     */
    public static void doHttpGetRequest(final Context context, String url, RequestParams params, boolean showLoading, final RequestResponseListener listener) {
        mFlagShowLoading = showLoading;
        doHttpGetRequest(context, url, params, listener);
    }

    public static void doHttpGetRequest(final Context context, String url, RequestParams params, final RequestResponseListener listener) {
        showLoadingDialog();
        new AsyncHttpClient().get(context, url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (listener != null) {
                    try {
                        String response = new String(responseBody, "Utf-8");
                        Loger.d("response----------->" + response);
                        listener.success(statusCode, response);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                hideLoadingDialog();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                if (listener != null) {
                    try {
                        if (responseBody != null) {
                            String response = new String(responseBody, "Utf-8");
                            Loger.d("response----------->" + response);
                            listener.failed(statusCode, response);
                        } else {
                            listener.failed(statusCode, context.getResources().getString(R.string.network_error));
                        }
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                hideLoadingDialog();
            }
        });
    }

    /**
     * Post请求带参数是否显示加载状态
     *
     * @param context
     * @param url
     * @param params
     * @param showLoading
     * @param listener
     */
    public static void doHttpPostRequest(final Context context, String url, RequestParams params, boolean showLoading, final RequestResponseListener listener) {
        mFlagShowLoading = showLoading;
        doHttpPostRequest(context, url, params, listener);
    }

    /**
     * Post请求
     *
     * @param context
     * @param url
     * @param params
     * @param listener
     */
    public static void doHttpPostRequest(final Context context, String url, RequestParams params, final RequestResponseListener listener) {
        showLoadingDialog();
        new AsyncHttpClient().post(context, url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (listener != null) {
                    try {
                        String response = new String(responseBody, "Utf-8");
                        Loger.d("response----------->" + response);
                        listener.success(statusCode, response);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                hideLoadingDialog();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                if (listener != null) {
                    try {
                        if (responseBody != null) {
                            String response = new String(responseBody, "Utf-8");
                            Loger.d("response----------->" + response);
                            listener.failed(statusCode, response);
                        } else {
                            listener.failed(statusCode, context.getResources().getString(R.string.network_error));
                        }
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                hideLoadingDialog();
            }
        });
    }

    /**
     * 上传文件请求
     *
     * @param context
     * @param url
     * @param params
     * @param listener
     */
    public static void doFileUploadRequest(final Context context, String url, RequestParams params, final FileUploadRequestResponseListener listener) {
        new AsyncHttpClient().post(context, url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (listener != null) {
                    try {
                        String response = new String(responseBody, "Utf-8");
                        Loger.d("response----------->" + response);
                        listener.success(statusCode, response);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                if (listener != null) {
                    try {
                        if (responseBody != null) {
                            String response = new String(responseBody, "Utf-8");
                            Loger.d("response----------->" + response);
                            listener.failed(statusCode, response);
                        } else {
                            listener.failed(statusCode, context.getResources().getString(R.string.network_error));
                        }
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onProgress(long bytesWritten, long totalSize) {
                super.onProgress(bytesWritten, totalSize);
                if (listener != null) {
                    listener.onprogress((int) bytesWritten, (int) totalSize);
                }
            }
        });
    }


    static void showLoadingDialog() {
        if (!mFlagShowLoading) {
            return;
        }
        if (mLoadingDialogBuilder == null) {
            mLoadingDialogBuilder = new DialogBuilderFactory<LoadingDialogBuilder>(context, DialogBuilderFactory.DialogType.LOADING).Builder();
        }
        mLoadingDialogBuilder.Show();
    }

    static void hideLoadingDialog() {
        if (!mFlagShowLoading) {
            return;
        }
        if (mLoadingDialogBuilder != null) {
            mLoadingDialogBuilder.Dismiss();
            mFlagShowLoading = false;
        }
    }

    public interface RequestResponseListener {
        void success(int statuscode, String response);

        void failed(int statuscode, String response);
    }

    public interface FileUploadRequestResponseListener extends RequestResponseListener {
        void onprogress(int bytesWritten, int totalSize);
    }


    /**
     * 获取请求返回的状态码
     *
     * @param response
     * @return
     */
    public static String getResponseCode(String response) {
        try {
            JSONObject json = new JSONObject(response);
            return json.getString("status");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getResponseErrorMsg(String response) {
        String errormsg = "";
        try {
            JSONObject json = new JSONObject(response);
            JSONObject data = null;
            try {
                data = json.getJSONObject("data");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (data != null) {
                errormsg = data.getString("msg");
            } else {
                errormsg = json.getString("msg");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return errormsg;
    }


    public static JSONObject getResponseData(String response) {
        try {
            JSONObject json = new JSONObject(response);
            return json.getJSONObject("data");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;

    }

    public static JSONArray getResponseDataArray(String response) {
        try {
            JSONObject json = new JSONObject(response);
            return json.optJSONArray("data");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;

    }


    public static class ResponseCode {
        public static String api_code_200 = "200";
        public static String api_code_10001 = "10001";
        public static String api_code_10002 = "10002";
        public static String api_code_10003 = "10003";
        public static String api_code_10004 = "10004";
        public static String api_code_10005 = "10005";
        public static String api_code_10006 = "10006";
        public static String api_code_11001 = "11001";
        public static String api_code_11002 = "11002";
        public static String api_code_11003 = "11003";
        public static String api_code_11004 = "11004";
        public static String api_code_11005 = "11005";
        public static String api_code_50001 = "50001";
        public static String api_code_50002 = "50002";
        public static String api_code_50003 = "50003";
        public static String api_code_50004 = "50004";
    }

    /**
     * 获取请求码对应的中文信息
     *
     * @param code
     * @return
     */
    public static String getResponseStateMessage(String code) {
        int resId = context.getResources().getIdentifier("api_code_" + code, "string", context.getPackageName());
        return resId > 0 ? context.getString(resId) : null;
    }


}
